/**
 * 退出房间
 * Created by duwei on 2018/5/2.
 */
var RoomQuitWindow = Window.extend({
    _ccsFileName : res.RoomQuitWindow_json,
    /**
     * 等待文字颜色
     * @private
     */
    dengdaiColor: cc.color("#E82020"),
    /**
     * 同意文字颜色
     * @private
     */
    tongyiColor: cc.color("#10AA00"),
    /**
     * 拒绝文字颜色
     * @private
     */
    jujueColor: cc.color("#E82020"),
    _initClickListeners: function () {
        this._super();
        this._clickListeners = {
            'root.btn_ok': '_clickOk',
            'root.btn_confirm': '_clickConfirm',
            'root.btn_cancel': '_clickCancel',
        };
    },
    /**
     * 点击确定
     * @private
     */
    _clickOk: function () {
        var self = this;
        self.setVisible(false);

        if(self.callback){
            self.callback();
        }
    },
    /**
     * 点击同意
     * @private
     */
    _clickConfirm: function () {
        var self = this;
        if (self.JieSanData['Users']) {
            network.wsData(['Vote', 'quit', 1, 0, 0].join('/'));
        } else {
            network.send(3009, {room_id: gameData.roomId, is_accept: 1});
        }
    },
    /**
     * 点击取消
     * @private
     */
    _clickCancel: function () {
        var self = this;
        if (self.JieSanData['Users']) {
            network.wsData(['Vote', 'quit', 2, 0, 0].join('/'));
        } else {
            network.send(3009, {room_id: gameData.roomId, is_accept: 0});
        }
    },
    /**
     * 头像坐标
     * @private
     */
    getPos: function (index) {
        var self = this;
        var posX = 0;
        if (self.playerCount / 2 > 2) {//两行
            var count = Math.floor(self.playerCount / 2 + 0.5);
            if (index < count) {
                posX = self.getPosX(count, index);
            } else {
                var curCount = self.playerCount - count;
                posX = self.getPosX(curCount, index - count);
            }
        } else {
            posX = self.getPosX(self.playerCount, index);
        }
        var posY = self.getPosY(index);
        return cc.p(posX, posY);
    },
    /**
     * 头像X坐标
     * @private
     */
    getPosX: function (length, index) {
        var self = this;
        var intervalX = 150;
        var posX = self.infoNode.getContentSize().width / 2;
        var originX = posX - (length - 1) / 2 * intervalX;
        return originX + index * intervalX;
    },
    /**
     * 头像Y坐标
     * @private
     */
    getPosY: function (index) {
        var self = this;
        var intervalY = 140;
        var posY = self.infoNode.getContentSize().height / 2;
        var count = 4;
        var originY = posY;
        if (self.playerCount / 2 > 2) {//两行
            count = Math.floor(self.playerCount / 2 + 0.5);
            originY = posY + intervalY / 2;
        }
        return originY - Math.floor(index / count) * intervalY;
    },
    /**
     * 设置解散数据
     * @param leftSeconds 剩余时间
     * @param arr 操作数组
     * @param byUserID 发起者ID
     * @param data 3009数据结构
     * @public
     */
    refreshData: function (leftSeconds, arr, byUserID, data, callback) {
        var self = this;
        cc.log('refreshData');
        self.playerCount = gameData.players.length;
        self.infoNode = self._nodeList['root.infoNode'];
        self.JieSanData = data;
        self.callback = callback;

        self.infoMap = [];
        var acceptCount = 0;
        var refuseUid = data['refuse_uid'];
        for (var i = 0; i < self.playerCount; i++) {
            (function (i) {
                var info = self.infoNode.getChildByName("info" + i);
                if (!info) {
                    info = duplicateNode(self.infoNode["info0"]);
                    info.setName("info" + i);
                    self.infoNode.addChild(info);
                }
                info.setVisible(true);
                self.infoMap.push(info);
                var player = gameData.players[i];
                var infoData = info.getUserData();
                if (!infoData || infoData.uid != player.uid) {
                    infoData = {};
                    infoData.uid = player.uid;
                    info.setUserData(infoData);
                    var url = decodeURIComponent(player.headimgurl);
                    if (url == undefined || (url.length == 0)) url = res.defaultHead;
                    loadImageToSprite(url, info.getChildByName('head'));//头像
                    info.getChildByName('lb_name').setString(ellipsisStr(player.nickname, 4));
                }
                info.getChildByName('statusicon_jujue').setVisible(false);
                info.getChildByName('statusicon_tongyi').setVisible(false);
                info.getChildByName('statusicon_dengdai').setVisible(true);
                info.getChildByName('lb_status').setString("未选择");
                info.getChildByName('lb_status').setColor(self.dengdaiColor);
                if (data["Users"]) {
                    for (var k = 0; k < arr.length; k++) {
                        if (player.uid == arr[k]['UserID']) {
                            info.getChildByName('statusicon_dengdai').setVisible(false);
                            info.getChildByName('statusicon_tongyi').setVisible(arr[k]['VoteValue'] == 1);
                            info.getChildByName('statusicon_jujue').setVisible(arr[k]['VoteValue'] == 2);
                            cc.log(k);
                            cc.log('VoteValue == '+arr[k]['VoteValue']);
                            if (arr[k]['VoteValue'] == 1) {
                                info.getChildByName('lb_status').setString("已同意");
                                info.getChildByName('lb_status').setColor(self.tongyiColor);
                                acceptCount++;
                            } else if (arr[k]['VoteValue'] == 2) {
                                info.getChildByName('lb_status').setString("已拒绝");
                                info.getChildByName('lb_status').setColor(self.jujueColor);
                                refuseUid = arr[k]['UserID'];
                            }
                            break;
                        }
                    }
                } else {
                    for (var k = 0; k < arr.length; k++) {
                        if (player.uid == arr[k].uid) {
                            // cc.log(i,player.uid,arr[k]['is_accept']);
                            info.getChildByName('statusicon_dengdai').setVisible(false);
                            info.getChildByName('statusicon_tongyi').setVisible(arr[k]['is_accept'] == 1);
                            info.getChildByName('statusicon_jujue').setVisible(arr[k]['is_accept'] != 1);
                            info.getChildByName('lb_status').setString(arr[k]['is_accept'] == 1 ? "已同意" : "已拒绝");
                            info.getChildByName('lb_status').setColor(arr[k]['is_accept'] == 1 ? self.tongyiColor : self.jujueColor);
                            break;
                        }
                    }
                }
                info.setPosition(self.getPos(i));
            })(i);
        }
        for (; i <= self.infoNode.children.length; i++) {
            var info = self.infoNode["info" + i];
            if (info) {
                info.setVisible(false);
            }
        }

        //自己属否同意
        var haveISelected = false;
        if (data["Users"]) {
            for (var i = 0; i < arr.length; i++) {
                if ((arr[i].UserID == gameData.uid && (arr[i].VoteValue == 1 || arr[i].VoteValue == 2))) {
                    haveISelected = true;
                    break;
                }
            }
        } else {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i].uid == gameData.uid) {
                    haveISelected = true;
                    break;
                }
            }
        }
        var nickname = byUserID;
        if(gameData.playerMap[byUserID]){
            nickname = gameData.playerMap[byUserID].nickname;
        }
        var content = "玩家【" + nickname + "】申请解散房间, "
            + (haveISelected ? "请等待其他玩家选择 (超过"+leftSeconds+"秒未做选择, 则默认同意)"
                : "请问是否同意? (超过"+leftSeconds+"秒未做选择, 则默认同意)");
        self._nodeList['root.lb_text'].setString(content);

        if (haveISelected) {
            self._nodeList['root.btn_confirm'].setVisible(false);
            self._nodeList['root.btn_cancel'].setVisible(false);
        } else {
            self._nodeList['root.btn_confirm'].setVisible(true);
            self._nodeList['root.btn_cancel'].setVisible(true);
        }

        self._nodeList['root.lb_result'].setVisible(false);
        self._nodeList['root.btn_ok'].setVisible(false);
        self._nodeList['root.lb_time'].setVisible(true);

        var isJiesan = data['is_jiesan'] || acceptCount == arr.length;
        if (isJiesan) {
            self._nodeList['root.btn_confirm'].setVisible(false);
            self._nodeList['root.btn_cancel'].setVisible(false);
            self._nodeList['root.btn_ok'].setVisible(true);
            self._nodeList['root.lb_result'].setVisible(true);
            self._nodeList['root.lb_result'].setString("投票结果为: 解散房间");
            self._nodeList['root.lb_time'].setVisible(false);
        }
        if (refuseUid) {
            self._nodeList['root.btn_confirm'].setVisible(false);
            self._nodeList['root.btn_cancel'].setVisible(false);
            self._nodeList['root.btn_ok'].setVisible(true);
            self._nodeList['root.lb_result'].setVisible(true);
            self._nodeList['root.lb_result'].setString('玩家【' + gameData.playerMap[refuseUid].nickname + '】拒绝，房间解散失败，游戏继续');
            self._nodeList['root.lb_time'].setVisible(false);
        }

        //如果是观战  只显示确定按钮
        if (gameData.isSelfWatching || gameData.isSitNotPlay) {
            self._nodeList['root.btn_confirm'].setVisible(false);
            self._nodeList['root.btn_cancel'].setVisible(false);
        }

        if (self.interval) {
            clearInterval(self.interval);
            self.interval = null;
        }
        var func = function () {
            if (leftSeconds <= 0 || !cc.sys.isObjectValid(self)) {
                clearInterval(self.interval);
                self.interval = null;
                return;
            }
            self._nodeList['root.lb_time'].setString("剩余时间:" + leftSeconds);
            leftSeconds--;
        };
        func();
        self.interval = setInterval(func, 1000);
    },
});